package uw10.app.display;

import uw10.app.data.Event;
import uw10.app.data.GraphBounds;
import uw10.app.data.GraphData;
import uw10.app.data.GraphIndicator;
import uw10.app.data.sources.EventGraphDataSource;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Bitmap.Config;
import android.graphics.Color;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

public class EventGraphView extends View implements OnTouchListener
{
	private Context context;
	
	private Event event;
	
	private EventGraphDataSource dataSource;
	
	private GraphRenderer renderer;
	private GraphBounds bounds;
	private Bitmap graph;
	
	private GraphData bid;
	private GraphData ask;
	private GraphIndicator[] news;
	private String title;
	
	private boolean ready;
	private boolean updateGraph;
	private boolean dataValid;
	
	public EventGraphView(Context context, AttributeSet attrs)
	{
		super(context, attrs);
		this.context = context;
		setOnTouchListener(this);
	}
	
	public void setup(GraphRenderer renderer, EventGraphDataSource dataSource)
	{
		this.renderer = renderer;
		this.dataSource = dataSource;
		graph = Bitmap.createBitmap(256, 256, Config.ARGB_8888);
	}
	
	public synchronized void setEvent(Event event)
	{
		this.event = event;
		if (dataSource != null)
		{
			bounds = dataSource.getGraphBounds(event);
			bid = dataSource.getBidData(event);
			ask = dataSource.getAskData(event);
			news = dataSource.getNewsIndicators(event);
			title = dataSource.getTitle(event);
			dataValid = (bounds != null && bid != null && ask != null && news != null && title != null);
		} else dataValid = false;
		updateGraph = true;
		ready = true;
		
		this.invalidate();
	}
	
	private void updateGraph()
	{
		graph.eraseColor(Color.BLACK);
		
		if (dataValid)
		{
			renderer.render(graph, bounds, bid, Color.RED, 2);
			renderer.render(graph, bounds, ask, Color.BLUE, 2);
			for (int i = 0; i < news.length; i++)
			{
				renderer.render(graph, bounds, news[i], Color.GREEN, 2, 5);
			}
			renderer.render(graph, title, GraphRenderer.LABEL_TITLE, Color.WHITE, 20);
		}
		else
		{
			renderer.render(graph, "No graph available!", GraphRenderer.LABEL_TITLE, Color.WHITE, 20);
		}
		
		updateGraph = false;
	}
	
	public synchronized void onDraw(Canvas c)
	{
		if (ready)
		{
			if (updateGraph) updateGraph();
			
			Rect src = new Rect(0, 0, graph.getWidth(), graph.getHeight());
			
			c.drawBitmap(graph, src, c.getClipBounds(), null);
		}
	}

	public boolean onTouch(View arg0, MotionEvent arg1)
	{
		return false;
	}
}
